package com.hitsz.application;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.hitsz.R;
import com.hitsz.global.Config;
import com.hitsz.global.UserInfor;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    OkHttpClient okHttpClient = new OkHttpClient();
    String TAG = "Cat";
    public String res = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.login_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // 登陆按钮
        if(view.getId() == R.id.login_button){
            EditText etUsername = (EditText)findViewById(R.id.username_editText);
            EditText etPassword = (EditText)findViewById(R.id.password_editText);

            String username = etUsername.getText().toString().trim();
            String password = etPassword.getText().toString().trim();

            // 登陆格式验证
            if((username.equals("") || password.equals(""))){
                // 用户名或密码为空
                Toast toast=Toast.makeText(this, "请输入账户名和密码！",Toast.LENGTH_SHORT);
                toast.show();
            }else if(!userNameMatch(username)){
                // 用户名格式错误
                Toast toast=Toast.makeText(this, "用户名应为5-15位,以字母开头且只包含字母 数字 _ -",Toast.LENGTH_SHORT);
                toast.show();
            }else if(!passwordMatch(password)){
                // 密码格式错误
                Toast toast=Toast.makeText(this, "密码应为5-20位,只包含字母 数字 _-,./@#",Toast.LENGTH_SHORT);
                toast.show();
            }
            else{
                postSend(username,password);

                // 睡三秒钟等待响应
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // res处理
                if(res.equals("")){
                    Toast toast=Toast.makeText(this, "登录响应超时！",Toast.LENGTH_SHORT);
                    toast.show();
                }else if(res.contains("\"status\":0")){
                    Toast toast=Toast.makeText(this, "登录成功！",Toast.LENGTH_SHORT);
                    toast.show();

                    // 修改当前状态为已登录
                    Config config = Config.getInstance();
                    config.setLogin(true);
                    UserInfor userInfor= UserInfor.getInstance();
                    userInfor.setUserName(username);
                    config.setUsername(username);

                    // 记录当前用户id
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        config.setUser_id(jsonObject.getString("user_id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    // 页面跳转
                    Intent intent = new Intent(LoginActivity.this, ModeSelectActivity.class);
                    startActivity(intent);
                    this.finish();
                }else{
                    Toast toast=Toast.makeText(this, "登录失败！\n用户名或密码错误！",Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        }
    }

    // 返回后只能回到主界面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            this.finish();
        }
        return true;
    }

    public void postSend(String username, String password){
        new Thread(){
            @Override
            public void run(){
        FormBody formBody = new FormBody.Builder()
                .add("username",username)
                .add("password",password).build();
        Request request = new Request.Builder()
                .url("http://192.168.56.1:3007/api/login")
                .post(formBody).build();
        Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    res = response.body().string();
                    Log.i(TAG,"body:"+res);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    // 用于匹配用户名是否符合规范 5-15位 以字母开头且只包含字母 数字 _ -
    private boolean userNameMatch(String userName){
        String pattern = "^[a-zA-Z][a-zA-Z0-9_-]{4,14}$";
        return (Pattern.matches(pattern, userName));
    }

    // 用于匹配密码是否符合规范 5-20位 只包含字母 数字 - _ , . / @ #
    private boolean passwordMatch(String password){
        String pattern = "^[a-zA-Z0-9_,./@#-]{5,20}$";
        return (Pattern.matches(pattern, password));
    }
}